package com.example.springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.Exception.ServiceException;
import com.example.springboot.common.Page;
import com.example.springboot.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;

/**
 * 商品分类表(Category)表服务实现类
 *
 * @author makejava
 * @since 2024-01-13 17:16:25
 */
@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductServiceImpl productService;
    @Autowired
    private OrdersServiceImpl ordersService;
    @Autowired
    private OrdersProductServiceImpl ordersProductService;


    /**
     * 获取所有用户信息
     *
     * @return
     */
    @Override
    public List<Category> selectAll() {
        return categoryMapper.selectAll();
    }

    /**
     * 根据ID删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        try {
            categoryMapper.deleteById(id);
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
    }


    /**
     * 根据ID更新信息
     *
     * @param category
     */
    @Override
    public void updateById(Category category) {
        try {
            categoryMapper.updateById(category);
        } catch (Exception e) {
            throw new ServiceException("更新失败");
        }
    }

    /**
     * 条件查询
     *
     * @param name
     * @param detail
     * @param status
     * @return
     */
    @Override
    public List<Category> selectByManyCondition(String name, String detail, Integer status) {
        try {
            return categoryMapper.selectByManyCondition(name, detail, status);
        } catch (Exception e) {
            throw new ServiceException("查询失败");
        }
    }

    /**
     * 分页查询
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public Page<Category> selectByPage(Integer currentPage, Integer pageSize) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 查询总记录数
            int totalCount = categoryMapper.selectAll().size();
            // 查询分页数据
            List<Category> users = categoryMapper.selectByPage(startRow, pageSize);

            // 封装返回结果
            Page<Category> page = new Page<>();
            page.setList(users);
            page.setTotal(totalCount);
            return page;
        } catch (ServiceException e) {
            throw new ServiceException("分页查询失败！");
        }

    }


    /**
     * 分页查询 条件查询
     *
     * @param currentPage
     * @param pageSize
     * @param name
     * @param detail
     * @param status
     * @return
     */
    @Override
    public Page<Category> selectByManyConditionInpage(Integer currentPage, Integer pageSize, String name, String detail, Integer status) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 查询总记录数
            int totalCount = categoryMapper.selectByManyCondition(name, detail, status).size();
            // 查询分页数据
            List<Category> users = categoryMapper.selectByManyConditionInpage(startRow, pageSize, name, detail, status);

            // 封装返回结果
            Page<Category> page = new Page<>();
            page.setList(users);
            page.setTotal(totalCount);
            return page;
        } catch (ServiceException e) {
            throw new ServiceException("条件查询失败！");
        }

    }

    /**
     * 分页查询 条件查询
     *
     * @param currentPage
     * @param pageSize
     * @param name
     * @param detail
     * @return
     */
    @Override
    public Page<Category> selectByManyConditionNoStatusInpage(Integer currentPage, Integer pageSize, String name, String detail) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 查询总记录数
            int totalCount = categoryMapper.selectByManyConditionNoStatus(name, detail).size();
            // 查询分页数据
            List<Category> users = categoryMapper.selectByManyConditionNoStatusInpage(startRow, pageSize, name, detail);

            // 封装返回结果
            Page<Category> page = new Page<>();
            page.setList(users);
            page.setTotal(totalCount);
            return page;
        } catch (ServiceException e) {
            throw new ServiceException("条件查询失败！");
        }

    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteByIds(List<Integer> ids) {
        try {
            for (Integer id : ids) {
                categoryMapper.deleteById(id);
            }
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
    }

    /**
     * 添加商户
     *
     * @param category
     */
    @Override
    public void addCategory(Category category) {
        Category categoryDB = null;
        try {
            // 先查询账号是否存在
            categoryDB = categoryMapper.selectByName(category.getName());
        } catch (ServiceException e) {
            throw new ServiceException("查询分类名称失败！");
        }

        if (categoryDB == null) {
            try {
                //  账号不存在，添加
                categoryMapper.addCategory(category);
            } catch (ServiceException e) {
                throw new ServiceException("添加失败");
            }
        } else {
            //  账号存在，抛出异常
            throw new ServiceException("分类名称已存在");
        }
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public Category selectById(Integer id) {
        try {
            return categoryMapper.selectById(id);
        } catch (Exception e) {
            throw new ServiceException("用户不存在");
        }
    }


    /**
     * 根据ID修改状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Integer id, Integer status) {
        if (StrUtil.isBlank(status.toString())) {
            throw new ServiceException("状态不能为空");
        }
        try {
            categoryMapper.updateStatus(id, status);
        } catch (Exception e) {
            throw new ServiceException("修改状态失败");
        }
    }

    /**
     * 根据ID修改用户信息
     *
     * @param category
     */
    @Override
    public void updateCategory(Category category) {
        try {
            categoryMapper.updateCategory(category);
        } catch (Exception e) {
            throw new ServiceException("修改用户信息失败");
        }
    }


    /**
     * 获取需要输入建议的商品分类
     *
     * @return
     */
    @Override
    public List<Category> loadAllCategory() {
        try {
            return categoryMapper.loadAllCategory();
        } catch (Exception e) {
            throw new ServiceException("获取需要输入建议的商品分类失败");
        }
    }


    /**
     * 获取TOP5的分类
     *
     * @return
     */
    @Override
    public List<Category> selectTop5Category() {
        // 获取所有分类
        List<Category> categories = categoryMapper.selectAll();

        // 根据分类ID获取该分类下的商品数量
        for (Category category : categories) {
            // 获取该分类下的商品数量
            BigDecimal productCount = productService.selectProductCountByCategoryId(category.getId());
            category.setProductCount(productCount);

            //  获取该分类下的订单数量
            BigDecimal orderCount = ordersService.selectOrderCountByCategoryId(category.getId());
            category.setOrderCount(orderCount);
        }


        // 按照商品数量降序排序
        categories.sort(Comparator.comparing(Category::getProductCount).reversed());

        // 截取前5个分类
        return categories.subList(0, 5);
    }


}
